import { NextRequest, NextResponse } from 'next/server';
import { readWords, writeWords, readPos } from '@/lib/data';
import { verifyToken } from '@/lib/auth';

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const token = request.cookies.get('token')?.value;
    const decoded = verifyToken(token || '');
    
    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '需要管理员权限' },
        { status: 403 }
      );
    }

    const body = await request.json();
    const { english, chinese, phonetic, categoryIds, senses } = body || {};
    const words = readWords();
    const word = words.find(w => w.id === params.id);

    if (!word) {
      return NextResponse.json(
        { success: false, message: '单词不存在' },
        { status: 404 }
      );
    }

    if (typeof english === 'string') {
      const nextEnglish = english.trim();
      if (!nextEnglish) {
        return NextResponse.json(
          { success: false, message: '单词（英文）不能为空' },
          { status: 400 }
        );
      }
      // 英文唯一性校验（不区分大小写）
      const key = nextEnglish.toLowerCase();
      const dup = words.some(w => w.id !== params.id && (w.english || '').trim().toLowerCase() === key);
      if (dup) {
        return NextResponse.json(
          { success: false, message: '英文单词已存在，不能重复' },
          { status: 400 }
        );
      }
      word.english = nextEnglish;
    }
    if (Array.isArray(categoryIds)) {
      const ids = categoryIds.map(String);
      word.categoryIds = ids.length ? Array.from(new Set(ids)) : undefined;
      word.categoryId = word.categoryIds?.[0] || '';
    }
    if (typeof chinese === 'string') word.chinese = chinese;
    if (phonetic !== undefined) word.phonetic = phonetic || undefined;
    if (Array.isArray(senses)) {
      const validPosIds = new Set(readPos().map(p => p.id));
      const sanitized = senses
        .map((s: any) => ({ posId: String(s.posId || ''), definitions: Array.isArray(s.definitions) ? s.definitions.map(String).filter(Boolean) : [] }))
        .filter(s => s.posId && validPosIds.has(s.posId) && s.definitions.length > 0);
      word.senses = sanitized.length ? sanitized : undefined;
    }
    writeWords(words);

    return NextResponse.json({ success: true, word });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '更新单词失败' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const token = request.cookies.get('token')?.value;
    const decoded = verifyToken(token || '');
    
    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '需要管理员权限' },
        { status: 403 }
      );
    }

    const words = readWords();
    const filtered = words.filter(w => w.id !== params.id);
    writeWords(filtered);

    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '删除单词失败' },
      { status: 500 }
    );
  }
}

